﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Xml.Linq;

namespace Comdiv.QWeb.Utils {
	public class XmlInterpolationPreprocessor {
		public void Execute(XElement xml) {
			process(xml);
		}

		private void process(XElement element) {
			foreach (var e in element.Elements()) {
				process(e);
			}
			foreach (var attr in element.Attributes()) {
				if (attr.Value.Contains("${")) {
					process(attr);
				}
			}
			var text = element.Nodes().OfType<XText>().FirstOrDefault();
			if (null != text && text.Value.Contains("${")) {
				process(text);
			}
		}

		private void process(XText e) {
			e.Value = process(e.Value, "_val_", e.Parent);
		}

		private void process(XAttribute attr) {
			attr.Value = process(attr.Value, attr.Name.LocalName, attr.Parent);
		}

		private string process(string val, string key, XElement e) {
			var replaces = new List<string>();
			val = Regex.Replace(val, @"\$\{[\s\S]+?\}", m =>
			                                            	{
			                                            		var r = m.Value.Substring(2, m.Value.Length - 3);
			                                            		int idx;
			                                            		if (replaces.Contains(r)) {
			                                            			idx = replaces.IndexOf(r);
			                                            		}
			                                            		else {
			                                            			replaces.Add(r);
			                                            			idx = replaces.Count - 1;
			                                            		}
			                                            		return "{" + idx + "}";
			                                            	});
			foreach (var r in replaces) {
				e.Add(new XElement("_p_", new XAttribute("k", key), r));
			}

			return val;
		}
	}
}